package manager.utility.thread;

import java.nio.ByteBuffer;
import java.util.ArrayList;

import manager.utility.QueueBackupObject;


public class LazyPersistingRawThread  extends Thread {

	private static QueueBackupObject bo;
	private ArrayList<ByteBuffer> ab;
	
	public LazyPersistingRawThread(ArrayList<ByteBuffer> memoryQueue) {
		bo=new QueueBackupObject();
		this.ab=memoryQueue;
		if(bo.getSize()>0)
			bo.loadBackup(ab);
	}
	
	public void run() {
		handleSynchro();
	}
	
	private synchronized void handleSynchro(){
		while(true){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			boolean trovato=true;
			while(trovato){
				bo.insertBlock(ab);
				long backupSize = bo.getSize();
				int memorySize = ab.size();
				 if(memorySize>backupSize)
					 trovato=true;
				 else
					 trovato=false;
			}
		 
		}
}

	public void removeMessage(){
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(bo.getSize()>0 && ab.size()>0){
			bo.remove();
			ab.remove(0);
		}
	}
}
